package com.ruoyi.releation.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.releation.domain.People;
import com.ruoyi.releation.domain.Releation;
import com.ruoyi.releation.mapper.PeopleMapper;
import com.ruoyi.releation.mapper.ReleationMapper;
import com.ruoyi.releation.service.IPeopleService;

/**
 * 人员 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class PeopleServiceImpl implements IPeopleService
{
    private static final Logger log = LoggerFactory.getLogger(PeopleServiceImpl.class);
    
    @Autowired
    private PeopleMapper peopleMapper;
    
    @Autowired
    private ReleationMapper releationMapper;

    /**
     * 根据条件分页查询人员列表
     * 
     * @param user 人员信息
     * @return 人员信息集合信息
     */
    @Override
    public List<People> selectPeopleList(People people)
    {
        return peopleMapper.selectPeopleList(people);
    }

    /**
     * 通过人员名查询人员
     * 
     * @param userName 人员名
     * @return 人员对象信息
     */
    @Override
    public People selectPeopleByName(String name)
    {
        return peopleMapper.selectPeopleByName(name);
    }


    /**
     * 通过人员ID查询人员
     * 
     * @param userId 人员ID
     * @return 人员对象信息
     */
    @Override
    public People selectPeopleById(Long id)
    {
        return peopleMapper.selectPeopleById(id);
    }

    /**
     * 通过人员ID删除人员
     * 
     * @param userId 人员ID
     * @return 结果
     */
    @Override
    public int deletePeopleById(Long id)
    {
        // 删除人员与角色关联
        releationMapper.deleteReleationByPeopleId(id);
        return peopleMapper.deletePeopleById(id);
    }

    /**
     * 批量删除人员信息
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deletePeopleByIds(String ids) throws BusinessException
    {
        Long[] peopleIds = Convert.toLongArray(ids);
        return peopleMapper.deletePeopleByIds(peopleIds);
    }

    /**
     * 新增保存人员信息
     * 
     * @param user 人员信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertPeople(People people)
    {
        // 新增人员信息
        int rows = peopleMapper.insertPeople(people);
        // 新增人员与角色管理
        insertReleation(people);
        return rows;
    }

    /**
     * 修改保存人员信息
     * 
     * @param user 人员信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updatePeople(People people)
    {
        //Long id = people.getId();
        // 删除人员与角色关联
        //releationMapper.deleteReleationByPeopleId(id);
        // 新增人员与角色管理
        //insertReleation(people);
        return peopleMapper.updatePeople(people);
    }

    /**
     * 修改人员个人详细信息
     * 
     * @param user 人员信息
     * @return 结果
     */
    @Override
    public int updatePeopleInfo(People people)
    {
        return peopleMapper.updatePeople(people);
    }

    /**
     * 新增人员角色信息
     * 
     * @param user 人员对象
     */
    public void insertReleation(People people)
    {
        
        Long[] ids = people.getReleationIds();
        if (StringUtils.isNotNull(ids))
        {
            // 新增人员与角色管理
            List<Releation> list = new ArrayList<Releation>();
            for (Long id : ids)
            {
                Releation r = new Releation();
                r.setFromId(people.getId());
                r.setFromName(people.getName());
                r.setToId(id);
                r.setToName(peopleMapper.selectPeopleById(id).getName());
                list.add(r);
            }
            if (list.size() > 0)
            {
                releationMapper.batchReleation(list);
            }
        }
    }

    /**
     * 校验登录名称是否唯一
     * 
     * @param loginName 人员名
     * @return
     */
    @Override
    public String checkNameUnique(String name)
    {
        int count = peopleMapper.checkNameUnique(name);
        if (count > 0)
        {
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }



    /**
     * 导入人员数据
     * 
     * @param peopleList 人员数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作人员
     * @return 结果
     */
    @Override
    public String importUser(List<People> peopleList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(peopleList) || peopleList.size() == 0)
        {
            throw new BusinessException("导入人员数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (People people : peopleList)
        {
            try
            {
                // 验证是否存在这个人员
                People p = peopleMapper.selectPeopleByName(people.getName());
                if (StringUtils.isNull(p))
                {
                    people.setCreateBy(operName);
                    this.insertPeople(people);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、人员 " + people.getName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    people.setUpdateBy(operName);
                    this.updatePeople(people);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、人员 " + people.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、人员 " + people.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、人员 " + people.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 人员状态修改
     * 
     * @param user 人员信息
     * @return 结果
     */
    @Override
    public int changeStatus(People people)
    {
        return peopleMapper.updatePeople(people);
    }

    @Override
    public List<Releation> selectReleationList() {
        
        return releationMapper.selectReleationList(new Releation());
    }

    @Override
    public int addReleation(Releation releation) {
        
        List<Releation> peopleList = new ArrayList<>();
        peopleList.add(releation);
        
        return releationMapper.batchReleation(peopleList);
    }

    @Override
    public int delReleation(Releation releation) {
        return releationMapper.deleteReleationInfo(releation);
    }

    @Override
    public List<Releation> selectReleationList(Releation releation) {
        return releationMapper.selectReleationList(releation);
    }

    @Override
    public Releation selectReleationById(Long id) {
        
        return releationMapper.selectReleationById(id);
    }

    @Override
    @Transactional
    public int updateReleation(Releation releation) {
        delReleation(releation);
        return addReleation(releation);
    }

    @Override
    public int deleteReleations(String ids) {
        Long[] releationIds = Convert.toLongArray(ids);
        
        return releationMapper.deleteReleation(releationIds);
    }

    @Override
    public String checkReleationUnique(Releation releation) {
        
        List<Releation> rs = releationMapper.selectReleationList(releation);
        
        if(rs.size() > 0) {
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }
}
